﻿using System;
using System.Text;
using RAP.Framework.Libary.Utils;
using RAP.Framework.Libary.DomTemplateBuilder.Element;
using RAP.Framework.Libary.DomTemplateBuilder.Configuration;
using RAP.Framework.Libary.DomTemplateBuilder.Interface;


namespace RAP.Framework.Libary.DomTemplateBuilder.Handler
{
	/// <summary>
	/// 引用配置的Handler
	/// </summary>
	public class IncludeHandler : HandlerBase
	{
		public override void DoRender ( StringBuilder writer, object rootParamObject, object parentParamObject, ITemplateRenderContext context )
		{
			var ele = this.Element as Include;
			var paramObj = this.GetParamObject ( rootParamObject, parentParamObject, context );
			var result = string.Empty;
			var tplItem = TemplateItem.FindTemplate ( ele.Template, ele.Name );
			if ( tplItem != null )
			{
				//如果存在指定名称局部子模板，则直接调用子模板
				result = TemplateItem.DoRender ( tplItem, rootParamObject, paramObj, context );
			}
			else
			{
				//查找并调用全局模板
				string fullName;
				if ( ele.Name.IndexOf ( '.' ) > 0 )
				{
					fullName = ele.Name;
				}
				else
				{
					//如果没有包含名称空间，则默认加上当前节点所属模板的名称空间
					fullName = string.Format ( "{0}.{1}", ele.Template.DomTemplate.NameSpace, ele.Name );
				}
				if ( TemplateItem.CheckTemplateAccessable ( this.Element.Template, fullName ) )
				{
					result = DomTemplateManager.Instance.RunTemplate ( fullName, rootParamObject, paramObj, context );
				}
				else
				{
					throw new Exception ( string.Format ( "访问者模板：{0} 不能访问模板：{1}。可能的原因是模板：{1}不存在或访问受限！", ele.Template.FullName, fullName ) );
				}
			}
			if ( result.IsNotNullOrEmpty ( ) )
			{
				writer.Append ( result );
			}
		}
	}
}
